<script setup>
import { userInfoUpdateService } from '@/api/user';
import { userAvatarUpdateService, userPasswordUpdateService } from '@/api/user.js';
import avatar from '@/assets/default.png';
import { useTokenStore } from '@/stores/token.js';
import useUserInfoStore from '@/stores/userInfo.js';
import {
CaretBottom,
Crop,
EditPen,
Goods,
Plus,
Shop,
ShoppingCart,
SwitchButton,
Ticket,
Upload,
User
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

// 状态管理与路由
const userInfoStore = useUserInfoStore();
const tokenStore = useTokenStore();
const router = useRouter();

// 响应式变量
const dialogVisible = ref(false);
const isConfirming = ref(false);
const ProfiledialogVisible = ref(false);
const formRef = ref(null);
const imgUrl = ref(userInfoStore.info?.avatar || ''); // 修复：添加可选链避免null报错
const avatarDialogvisible = ref(false);
const uploadRef = ref(null);
const pwdDialogVisible = ref(false);
const formRefPwd = ref(null);

// 表单数据
const formData = reactive({
  username: '',
  gender: '',
  studentNo: '',
  email: '',
  role: '',
  money: 0
});

// 密码修改数据
const resetData = reactive({
  userId: userInfoStore.info?.id || '', // 修复：添加可选链避免null报错
  oldPassword: '',
  password: '',
  rePassword: ''
});

// 邮箱验证规则
const checkEmail = (rule, value, callback) => {
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if (!emailReg.test(value)) {
    callback(new Error('请输入正确的邮箱格式'));
  } else {
    callback();
  }
};

// 确认密码验证（提前声明）
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== resetData.password) {
    callback(new Error('请确保两次输入的密码一致'));
  } else {
    callback();
  }
};

// 基本资料表单规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20个字符之间', trigger: 'blur' }
  ],
  studentNo: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: checkEmail, trigger: 'blur' }
  ]
};

// 密码表单规则
const rules1 = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码格式错误（5-16位）', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码格式错误（5-16位）', trigger: 'blur' }
  ],
  rePassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: checkRePassword, trigger: 'blur' }
  ]
};

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm(
      '您确定要退出登录吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      isConfirming.value = true;
      localStorage.clear();
      tokenStore.removeToken();
      userInfoStore.removeInfo();
      router.push('/user/login');
      ElMessage.success('退出登录成功');
      dialogVisible.value = false;
    }).catch(() => {
      if (!isConfirming.value) {
        ElMessage.info('退出登录取消');
      }
    });
  }
};

// 保存基本资料
const handleSave = async () => {
  if (!formRef.value) return; // 避免null调用
  try {
    await formRef.value.validate();
    const result = await userInfoUpdateService(formData);
    ElMessage.success(result.msg || '修改成功');
    userInfoStore.setInfo({ ...formData });
    ProfiledialogVisible.value = false;
  } catch (error) {
    return;
  }
};

// 关闭基本资料弹窗
const handleClose = () => {
  if (formRef.value) { // 避免null调用
    formRef.value.resetFields();
  }
  ProfiledialogVisible.value = false;
};

// 头像上传成功回调
const uploadSuccess = (result) => {
  imgUrl.value = `/photo/${result.data}`;
};

// 修改头像
const updateAvatar = async () => {
  try {
    const avatarData = {
      avatar: imgUrl.value
    };
    const result = await userAvatarUpdateService(avatarData);
    ElMessage.success(result.msg || '修改成功');
    if (userInfoStore.info) { // 避免null修改属性
      userInfoStore.info.avatar = imgUrl.value;
    }
    avatarDialogvisible.value = false;
  } catch (error) {
    ElMessage.error('头像修改失败');
    console.error('头像修改接口调用错误：', error);
  }
};

// 清空密码表单
const clearResetData = () => {
  resetData.oldPassword = '';
  resetData.password = '';
  resetData.rePassword = '';
};

// 修改密码
const updateUserPassword = async () => {
  if (!formRefPwd.value) return; // 避免null调用
  let isValid = false;
  try {
    await formRefPwd.value.validate();
    isValid = true;
  } catch (err) {
    console.log('表单验证失败:', err);
    isValid = false;
  }

  if (isValid) {
    try {
      const result = await userPasswordUpdateService(resetData);
      ElMessage.success(result.msg || '修改成功');
      userInfoStore.removeInfo();
      router.push('/login');
    } catch (error) {
      ElMessage.error('密码修改失败');
      console.log('密码修改失败:', error);
    }
  }
};

// 初始化
onMounted(() => {
  watch(() => ProfiledialogVisible.value, (newVal) => {
    Object.assign(formData, localStorage.getItem('user'));
    if (newVal && localStorage.getItem('user')) { // 确保数据存在
      
      console.log(localStorage.getItem('user'))
    }
  });
});
</script>

<template>
  <el-container class="layout-container">
    <!-- 左侧菜单 -->
    <el-aside width="200px">
      <div class="ink-title">文创文具</div>
      <el-menu
        :default-active="$route.path"
        active-text-color="#ffffff"
        background-color="#FFD166"
        text-color="#333333"
        router
        class="persistent-menu"
      >
        <el-menu-item index="/goods/market">
          <el-icon><Shop /></el-icon>
          <span>购物中心</span>
        </el-menu-item>
        <el-menu-item index="/goods/cart">
          <el-icon><ShoppingCart /></el-icon>
          <span>购物车</span>
        </el-menu-item>
        <el-menu-item index="/goods/order">
          <el-icon><Ticket /></el-icon>
          <span>我的订单</span>
        </el-menu-item>
        <el-menu-item index="/goods/manage">
          <el-icon><Goods /></el-icon>
          <span>商品管理</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧主区域 -->
    <el-container>
      <el-header background-color="#F96167">
        <div>欢迎使用该系统：<strong>{{ userInfoStore.info?.username || '访客' }}</strong></div>
        <el-dropdown placement="bottom-end" @command="handleCommand">
          <span class="el-dropdown__box">
            <el-avatar :src="userInfoStore.info?.avatar || avatar" />
            <el-icon><CaretBottom /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="ProfiledialogVisible = true" :icon="User">基本资料</el-dropdown-item>
              <el-dropdown-item @click="avatarDialogvisible = true" :icon="Crop">更换头像</el-dropdown-item>
              <el-dropdown-item @click="() => { pwdDialogVisible = true; clearResetData(); }" :icon="EditPen">重置密码</el-dropdown-item>
              <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>

      <el-main>
        <router-view></router-view>
      </el-main>

      <el-footer>校园跑腿平台 ©2025 Created by lioto & lay</el-footer>
    </el-container>
  </el-container>

  <!-- 修改基本资料弹窗 -->
  <el-dialog
    v-model="ProfiledialogVisible"
    title="基本资料"
    :width="500"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      label-width="100px"
      :rules="rules"
      style="margin-right: 30px;"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio label="MALE">男</el-radio>
          <el-radio label="FEMALE">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="学号" prop="studentNo">
        <el-input v-model="formData.studentNo" placeholder="请输入学号" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" type="email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="余额">
        <el-input
          :value="formData.money ? `${formData.money} 元` : ''"
          disabled
          placeholder="账户余额"
        />
      </el-form-item>
      <el-form-item label="身份">
        <el-input
          v-model="formData.role"
          disabled
          placeholder="用户身份"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="ProfiledialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>

  <!-- 修改头像弹窗 -->
  <el-dialog
    v-model="avatarDialogvisible"
    title="更换头像"
    :width="400"
    :close-on-click-modal="false"
  >
    <el-upload
      ref="uploadRef"
      class="avatar-uploader"
      :show-file-list="false"
      :auto-upload="true"
      action="http://localhost:8080/file/upload"
      name="file"
      :headers="{'Authorization': tokenStore.token}"
      :on-success="uploadSuccess"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <img v-else :src="avatar" width="278" alt="默认头像" />
    </el-upload>
    <br />
    <template #footer>
      <div class="avatar-dialog-footer">
        <el-button
          type="primary"
          :icon="Plus"
          @click="uploadRef?.$el?.querySelector('input')?.click()"
          class="avatar-dialog-btn"
        >
          选择图片
        </el-button>
        <el-button
          type="success"
          :icon="Upload"
          @click="updateAvatar"
          class="avatar-dialog-btn"
        >
          上传头像
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改密码弹窗 -->
  <el-dialog
    title="修改密码"
    v-model="pwdDialogVisible"
    :close-on-click-modal="false"
    width="500px"
    @close="pwdDialogVisible = false"
  >
    <el-form
      :rules="rules1"
      label-width="100px"
      size="large"
      :model="resetData"
      style="margin-right: 30px;"
      ref="formRefPwd"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          placeholder="请输入你的旧密码"
          type="password"
          v-model="resetData.oldPassword"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          placeholder="请输入你的新密码"
          type="password"
          v-model="resetData.password"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="rePassword">
        <el-input
          placeholder="请再次输入你的新密码"
          type="password"
          v-model="resetData.rePassword"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="pwdDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="updateUserPassword">提交修改</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.persistent-menu {
  :deep(.el-menu-item.is-active) {
    background-color: #FF9F1C !important;
    color: #FFFFFF !important;
    font-weight: 500;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-menu-item:not(.is-active):hover) {
    background-color: #FFE58F !important;
    color: #333333 !important;
  }

  :deep(.el-menu-item.is-active .el-icon) {
    color: inherit !important;
  }
  
  :deep(.el-menu-item) {
    margin: 4px 8px;
    transition: all 0.3s ease;
  }
}
.avatar-uploader {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
  
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
.avatar-dialog-footer {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 15px 0;
}

.avatar-dialog-btn:first-child {
  margin-right: 40px;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

.ink-title {
  font-family: "方正舒体";
  font-size: 30px;
  font-weight: bold;
  color: #333;
  text-align: center;
  padding: 20px 0;
  letter-spacing: 4px;
  text-shadow: 
    0 1px 0 #ccc,
    0 2px 0 #999,
    0 3px 3px rgba(0, 0, 0, 0.3);
  position: relative;
}

.ink-title::after {
  content: "";
  display: block;
  width: 60%;
  height: 2px;
  background: linear-gradient(to right, transparent, #888, transparent);
  margin: 5px auto 0;
}
.layout-container {
  
  height: 100vh; /* 占满整个视口高度 */
  margin: 0; /* 消除可能的默认 margin */
  display: flex;
  flex-direction: row;
  .el-aside {
    background-color: #FFD166;

    &__logo {
      height: 120px;
      background: url('@/assets/logo.png') no-repeat center / 120px auto;
    }

    .el-menu {
      border-right: none;
    }
  }

  .el-header {
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-dropdown__box {
      display: flex;
      align-items: center;

      .el-icon {
        color: #999;
        margin-left: 10px;
      }

      &:active,
      &:focus {
        outline: none;
      }
    }
  }

  .el-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
  }
}
</style>